package cn.supermaster.management.web.service.system.impl;

import cn.supermaster.management.common.configure.SMManagementConfiguration;
import cn.supermaster.management.common.constant.ShiroConstant;
import cn.supermaster.management.common.domain.SystemMenu;
import cn.supermaster.management.common.domain.SystemUser;
import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.text.Convert;
import cn.supermaster.management.common.utils.*;
import cn.supermaster.management.core.component.PasswordManager;
import cn.supermaster.management.system.service.ISystemConfigurationService;
import cn.supermaster.management.system.service.ISystemMenuService;
import cn.supermaster.management.web.service.system.ISIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.system.impl
 * @ClassName: SystemIndexServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/11 2:09
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.comn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class SIndexServiceImpl implements ISIndexService {

    @Autowired
    private ISystemMenuService menuService;

    @Autowired
    private ISystemConfigurationService configService;

    @Autowired
    private PasswordManager passwordService;

    /*
     * ================================================
     *  页面跳转功能实现
     * ================================================
     */

    /**
     * @Description: [跳转系统Index页面]
     * <p></P>
     * @Title: skipIndexHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipIndexHtml(ModelMap modelMap) {
        // 获取身份信息
        SystemUser user = ShiroUtils.getSystemUser();
        // 根据用户id取出菜单
        List<SystemMenu> menus = menuService.selectMenusByUser(user);
        modelMap.put("menus", menus);
        modelMap.put("user", user);
        modelMap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        modelMap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        modelMap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        modelMap.put("copyrightYear", SMManagementConfiguration.getCopyrightYear());
        modelMap.put("demoEnabled", SMManagementConfiguration.isDemoEnabled());
        modelMap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        modelMap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();

        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if (CheckUtils.isNotEmpty(cookieName) && "nav-style".equalsIgnoreCase(cookieName)) {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    /**
     * @Description: [跳转到系统锁屏界面]
     * <p></P>
     * @Title: skipLockscreenHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Return: java.lang.String
     */
    @Override
    public String skipLockscreenHtml(ModelMap modelMap) {
        //
        SystemUser user = getSystemUser();
        modelMap.put("user", user);
        ServletUtils.getSession().setAttribute(ShiroConstant.LOCK_SCREEN, true);
        return "lock";
    }

    /**
     * @Description: [跳转切换主题界面]
     * <p></P>
     * @Title: skipSwitchSkinHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Return: java.lang.String
     * @Throws:
     */
    @Override
    public String skipSwitchSkinHtml() {
        return "skin";
    }

    /**
     * @Description: [跳转切换菜单界面]
     * <p></P>
     * @Title: skipMenuStyleHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: response
     * @Param: style
     * @Return: void
     */
    @Override
    public void skipMenuStyleHtml(HttpServletResponse response, String style) {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    /**
     * @Description: [跳转系统主界面]
     * <p></P>
     * @Title: skipMainHtml
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: modelMap
     * @Return: java.lang.String
     * @Throws:
     */
    @Override
    public String skipMainHtml(ModelMap modelMap) {
        modelMap.put("version", SMManagementConfiguration.getVersion());
        return "main";
    }

    /*
     * ================================================
     *  Rest功能实现
     * ================================================
     */

    /**
     * @Description: [系统锁屏解锁处理]
     * <p></P>
     * @Title: doUnlockScreen
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: password 密码
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doUnlockScreen(String password) {
        SystemUser user = getSystemUser();
        if (CheckUtils.isNull(user)) {
            return WebResponse.failure("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password)) {
            ServletUtils.getSession().removeAttribute(ShiroConstant.LOCK_SCREEN);
            return WebResponse.success();
        }
        return WebResponse.failure("密码不正确，请重新输入。");
    }

    /*
     * ================================================
     *  通用功能实现
     * ================================================
     */

    /**
     * @Description: [获取用户信息]
     * <p></P>
     * @Title: getSystemUser
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Return: cn.supermaster.management.common.domain.SystemUser
     */
    private SystemUser getSystemUser() {
        SystemUser user = ShiroUtils.getSystemUser();
        return user;
    }

    /**
     * @Description: [检查初始密码是否提醒修改]
     * <p></P>
     * @Title: initPasswordIsModify
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: pwdUpdateDate
     * @Return: boolean
     */
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        String passwordModify = configService.selectConfigByKey("sys.account.initPasswordModify");
        Integer initPasswordModify = Convert.toInt(passwordModify);
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    /**
     * @Description: [检查密码是否过期]
     * <p></P>
     * @Title: passwordIsExpiration
     * @Author: Lance Ting
     * @Date: 2021-01-11
     * @Param: pwdUpdateDate
     * @Return: boolean
     */
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        String validateDays = configService.selectConfigByKey("sys.account.passwordValidateDays");
        Integer passwordValidateDays = Convert.toInt(validateDays);
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (CheckUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }

}